<?php
namespace app\rbac\model;
use think\Log;
use think\Session;
use think\Validate;
use think\Db;
use app\base\model\Base;
class AdminM extends Base
{

       protected function _V($scene,$data)
       {
           $rule = [
               'admin_name' => 'require',
               'email' => 'require|email',
               'password' => 'require|confirm',
               'login_password' => 'require',
               'old_password' => 'require',
           ];
        $msg = [
        'admin_name.require' => '管理员名称不能为空',
        'email.require' => '邮箱不能为空',
        'email.email' => '邮箱格式不正确',
        'password.require' => '密码不能为空',
        'password.confirm' => '密码不一致',
        'login_password.require' => '密码不能为空',
        'old_password.require' => '旧密码不能为空',
        ];
           $validate = new Validate($rule,$msg);
           $validate->scene('add', ['admin_name', 'email','password']);
           $validate->scene('edit', ['admin_name', 'email']);
           $validate->scene('login', ['admin_name', 'login_password']);
           $validate->scene('setPassword', ['password', 'old_password']);
           $validate->scene('editProfile', ['admin_name', 'email']);
           $result = $validate->scene($scene)->check($data);
           if($result === false)
           {
               return $validate->getError();
           }
           else
           {
               return true;
           }

       }

    /**
     * 登录
     * @param $data
     * @return bool
     */
       public function login($data)
       {
            $res = Db::table('admin')->where(['admin_name'=>$data['admin_name'],'is_usable'=>1])->find();
            if(!is_null($res) && md5($data['login_password']) == $res['password'])
            {
                Session::set('admin_id',$res['id']);
                Session::set('admin_name',$res['admin_name']);
                Session::set('admin_email',$res['email']);
                Session::set('admin_ico',$res['ico']);
                return true;
            }
            else
            {
                $this->code = -1;
                $this->msg = '用户名或者密码不正确!';
                return false;
            }
       }

    /**
     * 判断用户是否存在
     * @param $admin_name
     */
       private function isExist($admin_name)
       {
           return Db::table('admin')->where(['admin_name'=>$admin_name])->field('id')->find();
       }
    /**
     * 新增数据
     * @return mixed
     */

    public function add($data)
    {
        $res = $this->_V('add',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        if(!is_null($this->isExist($data['admin_name'])))
        {
            $this->code = -1;
            $this->msg = '用户已经存在';
            return false;
        }

        try{
            $id = Db::table('admin')->insertGetId(['admin_name'=>$data['admin_name'],'email'=>$data['email'],'password'=>md5($data['password']),'created_at'=>time(),'updated_at'=>time()]);
            $insertData = [];
            //角色
            foreach($data['role_id'] as $k=>$v)
            {
                $insertData[$k]['role_id'] = $v;
                $insertData[$k]['admin_id'] = $id;
            }
            Db::table('admin_role')->insertAll($insertData);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->code = -1;
            $this->msg = $e->getMessage();
            Db::rollback();
            return false;
        }
    }

    /**
     * 全部数据
     */
    public function lst()
    {
        $data = Db::table('admin')
            ->alias('a')
            ->field('a.id,a.admin_name,a.email,a.created_at,a.updated_at,GROUP_CONCAT(r.role_name) as role_names ')
            ->join('admin_role ar','ar.admin_id = a.id','LEFT')
            ->join('role r','r.id = ar.role_id','LEFT')
            ->where(['a.is_usable'=>1])
            ->group('a.id')
            ->paginate(15);
        return $data;
    }

    /**
     * 修改数据
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $res = $this->_V('edit',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $res2 = Db::table('admin')->where('id','<>',$data['id'])->where('admin_name',$data['admin_name'])->field('id')->find();
        if(!is_null($res2))
        {
            $this->code = -1;
            $this->msg = '用户已经存在';
            return false;
        }

            $insertData = [];
            //角色
            foreach($data['role_id'] as $k=>$v)
            {
                $insertData[$k]['role_id'] = $v;
                $insertData[$k]['admin_id'] = $data['id'];
            }
        try{
            Db::table('admin')->where(['id'=>$data['id']])->update(['admin_name'=>$data['admin_name'],'email'=>$data['email'],'updated_at'=>time()]);
            Db::table('admin_role')->where(['admin_id'=>$data['id']])->delete();
            Db::table('admin_role')->insertAll($insertData);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->code = -1;
            $this->msg = $e->getMessage();
            Db::rollback();
            return false;
        }
    }

    /**
     * 删除数据
     * @param $id
     */
    public function del($id)
    {
        // 启动事务
        Db::startTrans();
        try{
            Db::table('admin')->where('id',$id)->update(['is_usable'=>0]);
            Db::table('admin_role')->where('admin_id',$id)->delete();
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->code = -1;
            $this->msg = $e->getMessage();
            Db::rollback();
            return false;
        }


    }

    /**
     * 修改密码
     * @param $data
     * @return bool
     */
    public function setPassword($data)
    {
        $res = $this->_V('setPassword',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $admin_id = session('admin_id');
        $res = Db::table('admin')->where(['id'=>$admin_id,'is_usable'=>1])->field('password')->find();
        if(is_null($res) || $res['password'] !=md5($data['old_password']))
        {
            $this->code = -1;
            $this->msg = '旧密码不正确!';
            return false;
        }
        $res1 = Db::table('admin')->where('id',$admin_id)->update(['password'=>md5($data['password']),'updated_at'=>time()]);
        if(!$res1)
        {
            $this->code = -1;
            $this->msg = '修改密码失败';
            return false;
        }
        return true;
    }

    /**
     * 修改个人信息
     * @param $data
     * @return bool
     */
    public function editProfile($data)
    {
        $admin_id = session('admin_id');
        $res = $this->_V('editProfile',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        //处理图片

            $ret = uploadOne('ico', array(
                array(100, 100),
            ));
            if($ret['ok'] == 1)
            {
                $ico = toQiNiu($ret['images'][1]);   // 第一个缩略图地址
            }
            else
            {
                $this->code = -1;
                $this->msg = $ret['error'];
                return FALSE;
            }

        $res1 = Db::table('admin')->where('id',$admin_id)->update(['admin_name'=>$data['admin_name'],'email'=>$data['email'],'ico'=>$ico]);
        if(!$res1)
        {
            $this->code = -1;
            $this->msg = '修改失败!';
            return false;
        }
        return true;
    }

    /**
     * 判断是不是超级管理员
     * @param $admin_id
     * @return bool
     */
    public function isAdmin($admin_id)
    {
        if($admin_id == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 判断是否对特定表的字段有权限
     * @param $id
     * @param $table
     * @return bool
     */
    public function isAuth($id,$table,$post_id = 'id')
    {
        if(request()->isPost())
        {
            $id = request()->post($post_id);
        }
        //判断权限
        $admin_id = session('admin_id');
        $res1 = $this->isAdmin($admin_id);
        $res2 = Db::table($table)->where('id',$id)->field('admin_id')->find();
        if($res1 === true || $res2['admin_id'] == $admin_id)
        {
            return true;
        }
        return false;
    }
}
